<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <BackButton></BackButton>
      <p>商家信息</p>
    </header>
    <!-- 商家logo部分 -->
    <div class="business-logo">
      <img :src="business.businessImg" />
    </div>
    <!-- 商家信息部分 -->
    <div class="business-info">
      <h1>{{ business.businessName }}</h1>
      <p>
        &#165;{{ business.starPrice }}起送 &#165;{{
          business.deliveryPrice
        }}配送
      </p>
      <p>{{ business.businessExplain }}</p>
    </div>
    <!-- 食品列表部分 -->
    <ul class="food">
      <li v-for="(item, index) in foodArr">
        <div class="food-left">
          <img :src="item.foodImg" />
          <div class="food-left-info">
            <h3>{{ item.foodName }}</h3>
            <p>{{ item.foodExplain }}</p>
            <p>&#165;{{ item.foodPrice }}</p>
          </div>
        </div>
        <div class="food-right">
          <div>
            <i
              class="fa fa-minus-circle"
              @click="minus(index)"
              v-show="item.quantity != 0"
            ></i>
          </div>
          <p>
            <span v-show="item.quantity != 0">{{ item.quantity }}</span>
          </p>
          <div>
            <i class="fa fa-plus-circle" @click="add(index)"></i>
          </div>
        </div>
      </li>
    </ul>
    <!-- 购物车部分 -->
    <div class="cart">
      <div class="cart-left" @click="showPopup">
        <div
          class="cart-left-icon"
          :style="
            totalQuantity == 0
              ? 'background-color:#505051;'
              : 'background-color:#3190E8;'
          "
        >
          <i class="fa fa-shopping-cart"></i>
          <div class="cart-left-icon-quantity" v-show="totalQuantity != 0">
            {{ totalQuantity }}
          </div>
        </div>
        <div class="cart-left-info">
          <p>&#165;{{ totalPrice }}</p>
          <p>另需配送费{{ business.deliveryPrice }}元</p>
        </div>
      </div>
      <div class="cart-right">
        <!-- 不够起送费 -->
        <div
          class="cart-right-item"
          v-show="totalSettle < business.starPrice"
          style="background-color: #535356; cursor: default"
        >
          &#165;{{ business.starPrice }}起送
        </div>
        <!-- 达到起送费 -->
        <div
          class="cart-right-item"
          @click="toOrder"
          v-show="totalSettle >= business.starPrice"
        >
          去结算
        </div>
      </div>
    </div>
    <CartPopup
      :cartItems="foodArr"
      v-model:visible="isPopupVisible"
      @close="isPopupVisible = false"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';

import axios from 'axios';
import BackButton from '@/components/backButton.vue';
import CartPopup from '@/components/CartPopup.vue';

const route = useRoute();
const router = useRouter();
const businessId = ref(route.query.businessId);
const business = ref({});
const foodArr = ref([]);

const isPopupVisible = ref(false);
const user = ref(JSON.parse(sessionStorage.getItem('user')) || {});
const fetchBusinessInfo = async () => {
  try {
    const response = await axios.get(`/businesses/${businessId.value}`);
    business.value = response.data.data;
  } catch (error) {
    console.error(error);
  }
};

const fetchFoods = async () => {
  try {
    const response = await axios.get(`/foods/${businessId.value}`);
    foodArr.value = response.data.data.map(item => ({ ...item, quantity: 0 }));
    if (user.value) {
      await listCart();
    }
  } catch (error) {
    console.error(error);
  }
};

const listCart = async () => {
  try {
    const response = await axios.get(`/carts`, {
      params: {
        businessId: businessId.value,
        userId: user.value.userId,
      },
    });
    const cartArr = response.data.data;
    foodArr.value.forEach(foodItem => {
      foodItem.quantity = cartArr.reduce((acc, cartItem) => {
        return cartItem.foodId === foodItem.foodId ? acc + cartItem.quantity : acc;
      }, 0);
    });
    foodArr.value.sort();
  } catch (error) {
    console.error(error);
  }
};

const add = async (index) => {
  if (!user.value) {
    router.push({ path: '/login' });
    return;
  }
  if (foodArr.value[index].quantity === 0) {
    await saveCart(index);
  } else {
    await updateCart(index, 1);
  }
};

const minus = async (index) => {
  if (!user.value) {
    router.push({ path: '/login' });
    return;
  }
  if (foodArr.value[index].quantity > 1) {
    await updateCart(index, -1);
  } else {
    await removeCart(index);
  }
};

const saveCart = async (index) => {
  try {
    const response = await axios.post('/carts', {
      businessId: businessId.value,
      userId: user.value.userId,
      foodId: foodArr.value[index].foodId,
    });
    if (response.data.state === 200) {
      foodArr.value[index].quantity = 1;
      foodArr.value.sort();
    } else {
      alert('食品库存不足，向购物车中添加食品失败！');
    }
  } catch (error) {
    console.error(error);
  }
};

const updateCart = async (index, num) => {
  try {
    const response = await axios.put('/carts', {
      businessId: businessId.value,
      userId: user.value.userId,
      foodId: foodArr.value[index].foodId,
      quantity: foodArr.value[index].quantity + num,
    });
    if (response.data.state === 200) {
      foodArr.value[index].quantity += num;
      foodArr.value.sort();
    } else {
      alert(response.data.message);
    }
  } catch (error) {
    console.error(error);
  }
};

const removeCart = async (index) => {
  try {
    const response = await axios.delete('/carts', {
      data: {
        businessId: businessId.value,
        userId: user.value.userId,
        foodId: foodArr.value[index].foodId,
      },
    });
    if (response.data.state === 200) {
      foodArr.value[index].quantity = 0;
      foodArr.value.sort();
    } else {
      alert('从购物车中删除食品失败！');
    }
  } catch (error) {
    console.error(error);
  }
};

const toOrder = () => {
  router.push({
    path: '/orders',
    query: {
      businessId: business.value.businessId,
    },
  });
};

const showPopup = () => {
  isPopupVisible.value = !isPopupVisible.value;
};

onMounted(async () => {
  await fetchBusinessInfo();
  await fetchFoods();
});

const totalPrice = computed(() => {
  return foodArr.value.reduce((total, item) => total + item.foodPrice * item.quantity, 0);
});

const totalQuantity = computed(() => {
  return foodArr.value.reduce((total, item) => total + item.quantity, 0);
});

const totalSettle = computed(() => {
  return totalPrice.value + business.value.deliveryPrice;
});
</script>
<style scoped>
.wrapper {
  width: 100%;
  padding-bottom: 14vw;
}
.wrapper header {
  width: 100%;
  height: 12vw;
  background-color: #0097ff;
  color: #fff;
  font-size: 4.8vw;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
}
.wrapper .business-logo {
  width: 100%;
  height: 35vw;
  margin-top: 12vw;
  display: flex;
  justify-content: center;
  align-items: center;
}
.wrapper .business-logo img {
  width: 40vw;
  height: 30vw;
  border-radius: 5px;
}
.wrapper .business-info {
  width: 100%;
  height: 20vw;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.wrapper .business-info h1 {
  font-size: 5vw;
}
.wrapper .business-info p {
  font-size: 3vw;
  color: #666;
  margin-top: 1vw;
}
.wrapper .food {
  width: 100%;
  margin-bottom: 14vw;
}
.wrapper .food li {
  width: 100%;
  box-sizing: border-box;
  padding: 2.5vw;
  user-select: none;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.wrapper .food li .food-left {
  display: flex;
  align-items: center;
}
.wrapper .food li .food-left img {
  width: 20vw;
  height: 20vw;
}
.wrapper .food li .food-left .food-left-info {
  margin-left: 3vw;
}
.wrapper .food li .food-left .food-left-info h3 {
  font-size: 3.8vw;
  color: #555;
}
.wrapper .food li .food-left .food-left-info p {
  font-size: 3vw;
  color: #888;
  margin-top: 2vw;
}
.wrapper .food li .food-right {
  width: 16vw;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.wrapper .food li .food-right .fa-minus-circle {
  font-size: 5.5vw;
  color: #999;
  cursor: pointer;
}
.wrapper .food li .food-right p {
  font-size: 3.6vw;
  color: #333;
}
.wrapper .food li .food-right .fa-plus-circle {
  font-size: 5.5vw;
  color: #0097ef;
  cursor: pointer;
}
.wrapper .cart {
  width: 100%;
  height: 14vw;
  position: fixed;
  left: 0;
  bottom: 0;
  display: flex;
  z-index: 1000;
}
.wrapper .cart .cart-left {
  flex: 2;
  background-color: #505051;
  display: flex;
}
.wrapper .cart .cart-left .cart-left-icon {
  width: 16vw;
  height: 16vw;
  box-sizing: border-box;
  border: solid 1.6vw #444;
  border-radius: 8vw;
  background-color: #3190e8;
  font-size: 7vw;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: -4vw;
  margin-left: 3vw;
  position: relative;
}
.wrapper .cart .cart-left .cart-left-icon-quantity {
  width: 5vw;
  height: 5vw;
  border-radius: 2.5vw;
  background-color: red;
  color: #fff;
  font-size: 3.6vw;
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  right: -1.5vw;
  top: -1.5vw;
}
.wrapper .cart .cart-left .cart-left-info p:first-child {
  font-size: 4.5vw;
  color: #fff;
  margin-top: 1vw;
}
.wrapper .cart .cart-left .cart-left-info p:last-child {
  font-size: 2.8vw;
  color: #aaa;
}
.wrapper .cart .cart-right {
  flex: 1;
}
.wrapper .cart .cart-right .cart-right-item {
  width: 100%;
  height: 100%;
  background-color: #38ca73;
  color: #fff;
  font-size: 4.5vw;
  font-weight: 700;
  user-select: none;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
